<template>
  <div>
    <el-form-item>
      <label>SEO标题</label>
      <el-input v-model="form.seo_title" :maxlength="100" />
    </el-form-item>
    <el-form-item>
      <label>SEO关键词</label>
      <el-select
        v-model="form.tags"
        multiple
        filterable
        remote
        :remote-method="remoteMethod"
        :loading="loading"
        allow-create
        :multiple-limit="5"
        default-first-option
        style="width: 100%;"
        @change="handleChange"
      >
        <el-option
          v-for="item in options"
          :key="item.name"
          :label="item.name"
          :value="item.name"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <label>SEO描述</label>
      <el-input
        v-model="form.seo_description"
        type="textarea"
        :rows="4"
        :maxlength="200"
      />
    </el-form-item>
  </div>
</template>

<script>
import { getList } from '@/api/tag'

const defaultForm = {
  seo_title: '',
  tags: [],
  seo_description: '',
}
export default {
  name: 'SeoForm',
  props: {
    formData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      options: null,
      loading: false,
      form: []
    }
  },
  watch: {
    'form.seo_title': {
      handler(val) {
        this.formData.seo_title = val
      }
    },
    'form.tags': {
      handler(val) {
        this.formData.tags = val
      }
    },
    'form.seo_description': {
      handler(val) {
        this.formData.seo_description = val
      }
    }
  },
  created() {
    const data = this.$_.pick(this.formData, Object.keys(defaultForm))
    if (data.tags && data.tags.length > 0) {
      data.tags = data.tags.map((item) => { return item.name })
    }
    this.form = data
  },
  methods: {
    async remoteMethod(query) {
      if (query.trim() !== '') {
        this.loading = true;
        const response = await getList({ title: query.trim() })
        this.options = response.data
        this.loading = false
      } else {
        this.options = [];
      }
    },
    // select 值发生变化时我们将去纯空格项
    handleChange(v) {
      this.form.tags = v.filter(item => item.trim().length > 0)
    }
  }
}
</script>

<style>

</style>
